<template>
    <div id="register-page">
      <div class="page-top">
        <h1>登录</h1>
        <router-link to="/">回主页</router-link>
      </div>
      <form @submit.prevent="submitForm">
        <div>
          <label for="username">用户名：</label>
          <input type="text" id="username" v-model="username" required />
        </div>
        <div>
          <label for="password">密码：</label>
          <input type="password" id="password" v-model="password" required />
        </div>
        <div>
          <label for="confirm-password">确认密码：</label>
          <input
            type="password"
            id="confirm-password"
            v-model="confirmPassword"
            required
          />
        </div>
        <button type="submit">注册</button>
      </form>
      <div>
      <p>已有账户？<router-link to="/login">立即登录</router-link></p>
    </div>
    </div>
  </template>
  
<script setup>
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  // import axios from 'axios';
  import request from '../api/request';
  
  const router = useRouter();
  const username = ref('');
  const password = ref('');
  const confirmPassword = ref('');
  
  async function submitForm() {
    if (password.value !== confirmPassword.value) {
      alert('两次输入的密码不一致，请重新输入');
      return;
    }
  
    try {
      const response = await request.post('register', {
        username: username.value,
        password: password.value,
      });
  
      const result = response.data;
  
      if (result.status === 'success') {
        localStorage.setItem('username', username.value);
        router.push('/');
      } else {
        alert(result.message);
      }
    } catch (error) {
      console.error('注册请求失败:', error);
      alert('注册失败，请重试。');
    }
  }
  </script>
  
  <style scoped>
  #register-page {
    width: 100%;
    max-width: 400px;
    margin: 0 auto;
    padding: 20px;
    box-sizing: border-box;
  }
  .page-top{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
  
  form {
    display: flex;
    flex-direction: column;
  }
  
  div {
    margin-bottom: 1rem;
  }
  
  label {
    display: block;
    margin-bottom: 0.5rem;
  }
  
  input {
    width: 100%;
    padding: 0.5rem;
    box-sizing: border-box;
  }
  
  button {
    background-color: #4caf50;
    color: white;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 1rem;
    font-weight: bold;
  }
  
  button:hover {
    background-color: #45a049;
  }
  </style>
  